<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore, UserRole } from '@/stores/userStore'
import { ElMessage, ElLoading } from 'element-plus'
import { login } from '@/services/userService'

// 获取用户状态管理
const userStore = useUserStore()
const router = useRouter()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
})

// 表单验证规则
const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

// 表单引用
const loginFormRef = ref()

// 加载状态
const loading = ref(false)

// 是否显示管理员信息
const showAdminInfo = ref(false)

// 动画效果相关
const loginBoxClass = ref('')

/**
 * 组件挂载时的动画效果
 */
onMounted(() => {
  // 添加进入动画类
  setTimeout(() => {
    loginBoxClass.value = 'login-box-show'
  }, 100)
})

/**
 * 处理登录表单提交
 */
const handleLogin = async () => {
  // 表单验证
  await loginFormRef.value.validate()

  loading.value = true
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '登录中...' })

  try {
    // 检查是否是管理员账号
    if (
      loginForm.username === userStore.adminAccount.username &&
      loginForm.password === userStore.adminAccount.password
    ) {
      // 管理员登录
      userStore.userInfo = {
        username: loginForm.username,
        role: UserRole.ADMIN,
      }
      userStore.isLoggedIn = true

      ElMessage.success('管理员登录成功')
      router.push('/admin/welcome')
    } else {
      // 普通用户登录
      const user = await login(loginForm.username, loginForm.password)

      if (user) {
        // 更新用户状态
        userStore.userInfo = {
          username: user.username,
          role: user.role as UserRole,
        }
        userStore.isLoggedIn = true

        ElMessage.success('登录成功')

        // 根据用户角色跳转到对应的欢迎页面
        if (user.role === UserRole.ADMIN) {
          router.push('/admin/welcome')
        } else if (user.role === UserRole.MANAGER) {
          router.push('/admin/welcome') // 管理人员也跳转到管理页面
        } else {
          router.push('/user/welcome')
        }
      } else {
        ElMessage.error('用户名或密码错误')
      }
    }
  } catch (error: any) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '登录失败，请重试')
  } finally {
    loadingInstance.close()
    loading.value = false
  }
}

/**
 * 跳转到注册页面
 */
const goToRegister = () => {
  router.push('/register')
}

/**
 * 切换显示/隐藏管理员信息
 */
const toggleAdminInfo = () => {
  showAdminInfo.value = !showAdminInfo.value
}

/**
 * 快速填充管理员账号
 */
const fillAdminAccount = () => {
  loginForm.username = userStore.adminAccount.username
  loginForm.password = userStore.adminAccount.password
}
</script>

<template>
  <div class="login-container">
    <!-- 背景元素 -->
    <div class="background-elements">
      <div class="mountain mountain-1"></div>
      <div class="mountain mountain-2"></div>
      <div class="mountain mountain-3"></div>
      <div class="cloud cloud-1"></div>
      <div class="cloud cloud-2"></div>
      <div class="cloud cloud-3"></div>
      <div class="rain"></div>
    </div>

    <div class="login-box" :class="loginBoxClass">
      <div class="login-header">
        <h1>巴中市滑坡风险预警系统</h1>
        <p>用户登录</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-position="top"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            :clearable="true"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">
            登录
          </el-button>
        </el-form-item>

        <div class="login-options">
          <el-button link type="primary" @click="goToRegister"> 没有账号？立即注册 </el-button>
          <el-divider direction="vertical" />
          <el-button link type="info" @click="toggleAdminInfo">
            {{ showAdminInfo ? '隐藏管理员信息' : '显示管理员信息' }}
          </el-button>
        </div>
      </el-form>

      <!-- 管理员账号提示 -->
      <div v-if="showAdminInfo" class="admin-info">
        <div class="admin-info-header">
          <span>管理员账号信息（测试环境）</span>
          <el-button type="primary" size="small" @click="fillAdminAccount">一键填充</el-button>
        </div>
        <p>管理员账号：{{ userStore.adminAccount.username }}</p>
        <p>管理员密码：{{ userStore.adminAccount.password }}</p>
        <p class="admin-note">注意：管理员账号不可通过注册页面创建</p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
  position: relative;
  overflow: hidden;
}

// 背景动画
@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

// 背景元素
.background-elements {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

// 山脉元素
.mountain {
  position: absolute;
  bottom: 0;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.2);
}

.mountain-1 {
  width: 80%;
  height: 60%;
  left: -10%;
  bottom: -40%;
}

.mountain-2 {
  width: 60%;
  height: 40%;
  right: -10%;
  bottom: -30%;
}

.mountain-3 {
  width: 50%;
  height: 30%;
  left: 30%;
  bottom: -20%;
}

// 云朵元素
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
}

.cloud-1 {
  width: 200px;
  height: 60px;
  top: 20%;
  left: 10%;
  animation: cloud-move 30s linear infinite;
}

.cloud-2 {
  width: 300px;
  height: 80px;
  top: 30%;
  right: -100px;
  animation: cloud-move 40s linear infinite;
}

.cloud-3 {
  width: 150px;
  height: 50px;
  top: 15%;
  left: 50%;
  animation: cloud-move 35s linear infinite reverse;
}

@keyframes cloud-move {
  0% {
    transform: translateX(-100px);
  }
  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

// 雨滴效果
.rain {
  position: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.3) 100%);
  background-size: 20px 100px;
  animation: rain 0.5s linear infinite;
  opacity: 0.2;
}

@keyframes rain {
  0% {
    background-position: 0px 0px;
  }
  100% {
    background-position: 0px 100px;
  }
}

// 登录框
.login-box {
  width: 400px;
  padding: 40px;
  border-radius: 15px;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  transition: all 0.5s ease;
  z-index: 10;
  opacity: 0;
  transform: translateY(20px);

  &.login-box-show {
    opacity: 1;
    transform: translateY(0);
  }

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.3);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 30px;

  h1 {
    font-size: 24px;
    color: #333;
    margin-bottom: 10px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }

  p {
    font-size: 18px;
    color: #666;
    position: relative;
    display: inline-block;

    &:after {
      content: '';
      position: absolute;
      width: 50px;
      height: 2px;
      background: #409eff;
      bottom: -8px;
      left: 50%;
      transform: translateX(-50%);
    }
  }
}

.login-form {
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
  }
}

.login-options {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 15px;
}

.admin-info {
  margin-top: 30px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
  animation: fadeIn 0.5s ease;

  .admin-info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    font-weight: bold;
    color: #409eff;
  }

  p {
    margin: 5px 0;
    color: #666;
    font-size: 14px;
  }

  .admin-note {
    font-style: italic;
    color: #f56c6c;
    margin-top: 10px;
    font-size: 12px;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
